var webim = require('../../../utils/webim.js');
var webimhandler = require('../../../utils/webim_handler.js');
var tls = require('../../../utils/tls.js');


var Config = {
  sdkappid: 1400068801,
  accountType: 22679,
  accountMode: 1, //帐号模式，0-表示独立模式，1-表示托管模式
  avChatRoomId: '@TGS#aVRUL5BFW'
};

tls.init({
  sdkappid: Config.sdkappid
});

var app = getApp();
var reply_str = '';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    show_box: false,
    video_fit: 'fillCrop',
    input_value: '',
    reply_text: '说点什么……',
    icon_list: [
      { icon: 'zan', text: '赞' ,func: 'zan'},
      { icon: 'reply', text: '评论', func: 'reply' },
      { icon: 'goods', text: '宝贝', func: 'showGoods' },
      { icon: 'share', text: '分享',func: 'share' },
      { icon: 'gif', text: '礼物', func: 'gift' },
    ],
    flow_list: [],
    is_share: false,
  },
  onLoad: function (options) {
    wx.showLoading({
      title: '加载中…',
    })
    var self = this
    //调用应用实例的方法获取全局数据
    app.getUserInfo1(function (userInfo) {
      //更新数据
      self.setData({
        userInfo: userInfo
      })
      self.login(function () {
        self.initIM(userInfo);
      });
    })
    app.ihttpGet('https://www.58zltc.com/api.php/Zhibo/room/id/' + options.id + '/openid/' + app.globalData.openid, res => {
      this.setData({
        info: res.data.data,
        id: options.id
      })
    });
    app.ihttpGet('https://www.58zltc.com/api.php/Quan/giftList', res => {
      this.setData({
        gift_list: res.data
      })
    });
  },
  follow: function (e) {
    var info = this.data.info;
    var that = this;
    wx.showLoading({
      title: '加载中…',
    })
    var data = {};
    data.openid = app.globalData.openid;
    data.follow_openid = info.member.openid;
    app.ihttpPost('https://www.58zltc.com/api.php/Quan/follow', data, function (res) {
      if (res.data.err_code === 0) {
        if (res.data.err_msg == '-1') {
          info.is_follow = false;
        } else {
          info.is_follow = true;
        }
        that.setData({
          info: info
        })
        wx.hideLoading()
      } else {
        wx.showToast({
          title: res.data.err_msg
        })
      }
    })
  },
  reBg: function () {
    this.setData({
      show_box: false,
      is_share:false,
      video_fit: 'fillCrop'
    })
  },
  zan: function (e) {
    wx.showLoading({
      title: '加载中…',
    })
    var info = this.data.info;
    var that = this;
    app.ihttpGet('https://www.58zltc.com/api.php/Zhibo/zan/openid/' + app.globalData.openid + '/id/' + that.data.id, function (res) {
      if (res.data.err_code === 0) {
        if (res.data.err_msg == '-1') {
          info.zan_num = parseInt(info.zan_num) - 1;
          info.is_zan = false;
        } else {
          info.zan_num = parseInt(info.zan_num) + 1;
          info.is_zan = true;
        }
        that.setData({
          info: info
        })
        wx.hideLoading()
      } else {
        wx.showToast({
          title: res.data.err_msg
        })
      }
    })
  },
  share: function () {
    this.setData({
      is_share: true,
      video_fit: 'contain'
    })
  },
  closeShare: function () {
    this.setData({
      is_share: false
    })
  },
  reply: function () {
    this.setData({
      is_share: false,
      show_box: 'reply',
      video_fit: 'contain'
    })
  },
  goShop: function(){
    wx.navigateTo({
      url: '/pages/shop/detail?shop_id='+ this.data.info.shop_id,
    })
  },
  setReply: function (e) {
    reply_str = e.detail.value;
  },
  goReply: function (e) {
    var nowTime = new Date();
    if (nowTime - this.data.tapTime < 1000) {
      return;
    }
    var self = this;
    var content = reply_str;
    if (!content.replace(/^\s*|\s*$/g, '')) return;
    webimhandler.onSendMsg(content, function () {
      self.setData({
        'tapTime': new Date(),
        'reply_str': ''
      });
      // wx.showToast({
      //   title: '评论成功！',
      // })
      self.reBg();
    })
  },
  gift: function (e) {
    var id = this.data.info.id;
    this.setData({
      show_box: 'gift',
      gift_id: id,
      video_fit: 'cover'
    })
  },
  showGoods: function(e){
    this.setData({
      show_box: 'goods',
      video_fit: 'cover'
    })
  },
  hiddenGift: function (e) {
    this.reBg();
  },
  setGift: function (e) {
    var idx = e.currentTarget.dataset.idx;
    let that = this;
    var gift_list = that.data.gift_list;
    gift_list.forEach(function (value, key) {
      gift_list[key].active = key == idx ? true : false;
    })
    this.setData({
      gift_list: gift_list,
      active_gift: gift_list[idx]
    })
  },
  payGift: function(e){
    let that = this;
    var data =this.data;
    var post_data = {};
    post_data.type = 'zhibo';
    post_data.to = data.info.member.openid;
    post_data.from = app.globalData.openid;
    post_data.id = data.id;
    post_data.gift_id = data.active_gift.id;
    
    app.ihttpPost('https://www.58zltc.com/api.php/Quan/payGift', post_data, function(res){
      if (res.data.err_code == 400) {
        wx.showToast({
          title: res.data.err_msg,
        })
      } else {
        var data = res.data;
        wx.requestPayment({
          'appId': data.appId,
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': 'MD5',
          'paySign': data.paySign,
          'success': res => {
            if (res.errMsg == 'requestPayment:ok') {
              wx.sendSocketMessage({
                data: JSON.stringify(post_data)
              })
            }
          }
        })
        that.reBg();
      }
    })
  },
  login: function (cb) {
    var self = this;
    tls.anologin(function (data) {
      self.setData({
        Identifier: data.Identifier,
        UserSig: data.UserSig
      })
      cb();
    });
  },
  receiveMsgs: function (data) {
    if (!data.content) {
      return;
    }
    var msg = restHTML(data.content);
    try {
      msg = JSON.parse(msg);
    } catch (e) {
      msg = msg;
    }
    msg = typeof (msg) == "object" ? msg.msg : msg;
    if (!msg) {
      return;
    }
    var flow_list = this.data.flow_list;
    if (data.fromAccountNick == '@TIM#SYSTEM'){
      if (data.content.indexOf(this.data.Identifier) >= 0){
        webimhandler.onSendMsg("加入了房间", function () {});
      }
    }else{
      flow_list.push({ nickname: data.fromAccountNick, content: data.content, type: 'reply' });
      this.setData({
        flow_list: flow_list
      });
    }
  },
  initIM: function (userInfo) {
    var self = this;
    // Config.avChatRoomId = self.data.id;
    webimhandler.init({
      accountMode: Config.accountMode,
      accountType: Config.accountType,
      sdkAppID: Config.sdkappid,
      avChatRoomId: Config.avChatRoomId,
      selType: webim.SESSION_TYPE.GROUP,
      selToID: Config.avChatRoomId,
      selSess: null //当前聊天会话
    });
    //当前用户身份
    var loginInfo = {
      'sdkAppID': Config.sdkappid, //用户所属应用id,必填
      'appIDAt3rd': Config.sdkappid, //用户所属应用id，必填
      'accountType': Config.accountType, //用户所属应用帐号类型，必填
      'identifier': self.data.Identifier, //当前用户ID,必须是否字符串类型，选填
      'identifierNick': userInfo.nickname, //当前用户昵称，选填
      'userSig': self.data.UserSig, //当前用户身份凭证，必须是字符串类型，选填
    };
    //监听（多终端同步）群系统消息方法，方法都定义在demo_group_notice.js文件中
    var onGroupSystemNotifys = {
      "5": webimhandler.onDestoryGroupNotify, //群被解散(全员接收)
      "11": webimhandler.onRevokeGroupNotify, //群已被回收(全员接收)
      "255": webimhandler.onCustomGroupNotify //用户自定义通知(默认全员接收)
    };

    //监听连接状态回调变化事件
    var onConnNotify = function (resp) {
      switch (resp.ErrorCode) {
        case webim.CONNECTION_STATUS.ON:
          //webim.Log.warn('连接状态正常...');
          break;
        case webim.CONNECTION_STATUS.OFF:
          webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
          break;
        default:
          webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
          break;
      }
    };


    //监听事件
    var listeners = {
      "onConnNotify": webimhandler.onConnNotify, //选填
      "onBigGroupMsgNotify": function (msg) {
        webimhandler.onBigGroupMsgNotify(msg, function (msgs) {
          self.receiveMsgs(msgs);
        })
      }, //监听新消息(大群)事件，必填
      "onMsgNotify": webimhandler.onMsgNotify, //监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
      "onGroupSystemNotifys": webimhandler.onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
      "onGroupInfoChangeNotify": webimhandler.onGroupInfoChangeNotify //监听群资料变化事件，选填
    };

    //其他对象，选填
    var options = {
      'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
      'isLogOn': false //是否开启控制台打印日志,默认开启，选填
    };

    if (Config.accountMode == 1) { //托管模式
      webimhandler.sdkLogin(loginInfo, listeners, options, Config.avChatRoomId);
    } else { //独立模式
      //sdk登录
      webimhandler.sdkLogin(loginInfo, listeners, options);
    }
  }
})
function restHTML(str) {
  if (typeof str != 'string') {
    return '' + str;
  }
  return str.replace(/&(lt|gt|amp|quot|#0?34|apos|#0?39);/g, function ($0, $1) {
    switch ($1) {
      case 'lt':
        return '<';
      case 'gt':
        return '>';
      case 'amp':
        return '&';
      case 'quot':
      case '#34':
      case '#034':
        return '"';
      case 'apos':
      case '#39':
      case '#039':
        return '\'';
    }
  });
}
function getRandomColor() {
  let rgb = []
  for (let i = 0; i < 3; ++i) {
    let color = Math.floor(Math.random() * 256).toString(16)
    color = color.length == 1 ? '0' + color : color
    rgb.push(color)
  }
  return '#' + rgb.join('')
}